﻿var Axial =
{
	CallScriptService: function(url, method, params, onSuccess, onFailure)
	{
		var xhr = new XMLHttpRequest() || new ActiveXObject('Microsoft.XMLHTTP');
		xhr.open('POST', url + '/' + method, true);
		xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
		xhr.onreadystatechange = function()
		{
			if (xhr.readyState != 4)
				return;
			if (xhr.status == 200)
				onSuccess(eval('(' + xhr.responseText + ')').d);
			if (xhr.status == 500)
				onFailure(eval('(' + xhr.responseText + ')'));
		};
		xhr.send(this.toJson(params));
	},
	
	CallPageMethod: function(methodName, params, onSuccess, onFailure)
	{
		var xhr = new XMLHttpRequest() || new ActiveXObject('Microsoft.XMLHTTP');
		xhr.open('POST', location.pathname + '/' + methodName, true);
		xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
		xhr.onreadystatechange = function()
		{
			if (xhr.readyState != 4)
				return;
			if (xhr.status == 200)
				onSuccess(eval('(' + xhr.responseText + ')').d);
			if (xhr.status == 500)
				onFailure(eval('(' + xhr.responseText + ')'));
		};
		xhr.send(this.toJson(params));
	},
	
	toJson: function(obj)
	{
		switch (typeof obj)
		{
			case 'object':
				if (obj)
				{
					var list = [];
					if (obj instanceof Array)
					{
						for (var i = 0; i < obj.length; i++)
							list.push(this.toJson(obj[i]));
						return '[' + list.join(',') + ']';
					}
					else
					{
						for (var prop in obj)
							list.push('"' + prop + '":' + this.toJson(obj[prop]));
						return '{' + list.join(',') + '}';
					}
				}
				else
				{
					return 'null';
				}
			case 'string':
				return '"' + obj.replace(/(["'])/g, '\\$1') + '"';
			case 'number':
			case 'boolean':
				return new String(obj);
		}
	},
	
	ArrayToObject: function(nameArray, valueArray)
	{
		var obj = { };
		for (var i in nameArray)
			obj[nameArray[i]] = valueArray[i];
		return obj;
	}
}